import backtrader as bt


# backtrader实现价格行为
class PriceActionStrategy(bt.Strategy):
    params = (
        ("stop_loss_pct", 0.02),  # 止损百分比
        ("take_profit_pct", 0.05),  # 止盈百分比
    )

    def __init__(self):
        self.previous_high = None
        self.previous_low = None
        self.order = None

    def next(self):
        if len(self.data) > 1:
            self.previous_high = self.data.high[-1]
            self.previous_low = self.data.low[-1]

            current_close = self.data.close[0]

            if current_close > self.previous_high:
                # 突破高点买入
                if not self.position:
                    self.order = self.buy()
            elif current_close < self.previous_low:
                # 突破低点卖出
                if self.position:
                    self.order = self.sell()

            if self.position:
                # 设置止损和止盈
                stop_loss_price = self.position.price * (1 - self.params.stop_loss_pct)
                take_profit_price = self.position.price * (
                    1 + self.params.take_profit_pct
                )

                if self.data.close[0] <= stop_loss_price:
                    self.close()
                elif self.data.close[0] >= take_profit_price:
                    self.close()

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    f"BUY EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            elif order.issell():
                self.log(
                    f"SELL EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            self.order = None

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Canceled/Margin/Rejected")

    def log(self, txt):
        dt = self.datas[0].datetime.date(0)
        print(f"{dt}, {txt}")


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(PriceActionStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
